from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from apps.areas.models import Area
from django.core.cache import cache
# Create your views here.

class ProvinceView(View):
    def get(self,request):
        #先读取缓存
        data_list = cache.get('province')

        #判断缓存是否存在
        if data_list is None:

            #查询数据                   filter(字段名_运算符) = 值
            areas = Area.objects.filter(parent__isnull=True)

            data_list = []
            #将查询出来的结果遍历
            for area in areas:
                data_list.append({
                    'id':area.id,
                    'name':area.name
                })
            cache.set('province', data_list, 24 * 3600)

        return JsonResponse({'code':0,'errmsg':'ok','province_list':data_list})

class SubAreaView(View):
    def get(self,request,parent_id):

        #获取缓存
        subs_list = cache.get('city%s' % parent_id)

        #判断缓存是否存在
        if subs_list is None:

            #1,获取市id
            #根据省市获取市id,方式1，
            areas = Area.objects.filter(parent_id = parent_id)
            #方式2
            # pro_city = Area.objects.get(id = parent_id)
            # areas = pro_city.area_set.all()

            #将查询到的结果遍历转换为字典
            subs_list = []
            for area in areas:
                subs_list.append({
                    'id':area.id,
                    'name':area.name
                })

            #存储缓存信息
            cache.set('city_%s'%parent_id,subs_list, 24 * 3600)
            #返回响应
            return JsonResponse({
                'code':0,
                'errmsg':'ok',
                'sub_data':{'subs':subs_list}
        })
